package com.cloudbroker.bcs.platform.dav.middle.service.base;

import java.util.List;

import javax.annotation.Resource;

import com.cloudbroker.bcs.common.entity.Markable;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.dao.base.TenantDAOBase;

public abstract class TenantServiceImplBase<T extends Markable, K> extends MycatServiceImplBase<T, K> {
    
    protected abstract TenantDAOBase<T, K> getDAO();
    
    @Resource
    private AsyncService<T, K> asyncService;
    
    @Override
    public T get(K key) {
        return getDAO().get(key, getTenantId());
    }
    
    @Override
    public void delete(K key) {
        asyncService.setDAO(this.getDAO());
        asyncService.delete(key, getTenantId());
    }
    
    @Override
    public void save(T entity) {
        if (entity instanceof Markable) {
            Markable markable = (Markable) entity;
            markable.setMycat_flag(ConfigValues.getMycatFlag());
            if (markable.getTenant_id() == null) {
                markable.setTenant_id(getTenantId());
            }
        }
        super.save(entity);
    }
    
    @Override
    public void update(T entity) {
        if (entity instanceof Markable) {
            Markable markable = (Markable) entity;
            if (markable.getTenant_id() == null) {
                markable.setTenant_id(getTenantId());
            }
        }
        asyncService.setDAO(this.getDAO());
        asyncService.update(entity);
    }
    
    @Override
    public List<T> query(T example) {
        if (example.getTenant_id() == null) {
            example.setTenant_id(getTenantId());
        }
        return super.query(example);
    }
    
    @Override
    public Integer count(T example) {
        if (example.getTenant_id() == null) {
            example.setTenant_id(getTenantId());
        }
        return super.count(example);
    }
    
    protected Integer getTenantId() {
        return HSBCPSBizDataContext.getTenantId();
    }
}
